package com.itheima.blog.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.blog.admin.dto.PageDto;
import com.itheima.blog.admin.domain.po.TBanner;
import com.itheima.blog.admin.dao.TBannerMapper;
import com.itheima.blog.admin.service.ITBannerService;
import com.itheima.blog.admin.vo.PageVO;
import com.itheima.blog.admin.vo.Result;
import com.itheima.blog.util.UserThreadLocalUtils;
import com.itheima.blog.util.AliOssUtil;
import com.itheima.common.domain.R;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 轮播图设置表 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-07-12
 */
@Service
@RequiredArgsConstructor
public class TBannerServiceImpl extends ServiceImpl<TBannerMapper, TBanner> implements ITBannerService {

    AliOssUtil aliOssUtil = new AliOssUtil();

    @Override
    public R uploadFile(MultipartFile file) throws Exception{

        if(file==null||file.getSize()<=0){
            return R.error("文件上传失败");
        }
        LocalDateTime now = LocalDateTime.now();
        String upload = aliOssUtil.upload(file.getBytes(),  UUID.randomUUID().toString());
        TBanner tBanner = new TBanner();
        tBanner.setCreateTime(now);
        tBanner.setUrl(upload);
        tBanner.setStatus(true);
        Integer adminUserId = UserThreadLocalUtils.getAdminUserId();
        tBanner.setUserId(adminUserId);
        save(tBanner);
        return R.ok(upload);
    }

    @Override
    public void deleteFile(List<Integer> ids) {
        this.removeBatchByIds(ids);
    }

    @Override
    public Result updateFile(MultipartFile file, Integer id) throws Exception{
        AliOssUtil aliOssUtil = new AliOssUtil();
        if(file==null||file.getSize()<=0){
            return Result.error("文件上传失败");
        }
        String upload = aliOssUtil.upload(file.getBytes(),  UUID.randomUUID().toString());
        TBanner tBanner = getById(id);
        tBanner.setUrl(upload);
        this.updateById(tBanner);
        return Result.success(upload);
    }

    @Override
    public PageVO<TBanner> selectAll(PageDto pageDto) {
        PageVO<TBanner> pageVO = new PageVO<>();
        IPage<TBanner> tBannerIPage = lambdaQuery().page(new Page<>()).setPages(pageDto.getPageNo()).setSize(pageDto.getPageSize());

        pageVO.setList(tBannerIPage.getRecords());
        pageVO.setPages(tBannerIPage.getPages());
        pageVO.setTotal(tBannerIPage.getTotal());

        return pageVO;
    }
}
